package com.pxene.dmp.job.task;

import java.io.BufferedWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pxene.dmp.bean.DomainUserFIX;
import com.pxene.dmp.bean.DomainUserFIX.Content;
import com.pxene.dmp.common.DateUtils;
import com.pxene.dmp.common.KVRequester;
import com.pxene.dmp.common.KVUrlGenerator;
import com.pxene.dmp.constant.BaseConstant;

public class DomainUserFIXTask implements Runnable {

	private final Map<String, String> params;
	private final BufferedWriter writer;
	private final CountDownLatch latch;

	private Log log = LogFactory.getLog(DomainUserFIXTask.class);
	private BufferedWriter bw;

	public DomainUserFIXTask(String index, String date, BufferedWriter writer, CountDownLatch latch,
			BufferedWriter bw) {
		this.params = new HashMap<String, String>();
		this.params.put("index", index);
		this.params.put("date", date);
		this.writer = writer;
		this.latch = latch;
		this.bw = bw;
	}

	@Override
	public void run() {
		String url = KVUrlGenerator.getCustUrl(BaseConstant.API_GET_DOMAINUSERFIX);
		KVRequester reqer = new KVRequester(url, params, bw);
		DomainUserFIX resp = (DomainUserFIX) reqer.execute(DomainUserFIX.class);
		if (resp != null) {
			if (resp.getCode() == 200) {
				try {
					Content data = resp.getData();
					writer.write(
							data.getAccount() + "|" + parseDomain(data.getDomains()) + "|" + data.getProvince() + "\n");
					bw.write("[SUCCESS] " + DateUtils.getNowFormat("yyyy-MM-dd HH:mm:ss") + " ["
							+ Thread.currentThread().getName() + "] [" + DomainUserFIXTask.class.getName() + "] "
							+ this.params + "\n");
				} catch (Exception e) {
					log.error(BaseConstant.LOG_PREFIX + params + "Write File Exception", e);
					try {
						bw.write("[ERROR] " + DateUtils.getNowFormat("yyyy-MM-dd HH:mm:ss") + " ["
								+ Thread.currentThread().getName() + "] [" + DomainUserFIXTask.class.getName() + "] "
								+ "<=ee-debug=>" + params + "Write File Exception:" + e + "\n");
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}
			} else {
				log.error(BaseConstant.LOG_PREFIX + params + "request fail:" + resp.getMessage());
				try
		        {
		          bw.write("[ERROR] " + DateUtils.getNowFormat("yyyy-MM-dd HH:mm:ss") + " [" + 
		            Thread.currentThread().getName() + "] [" + DomainUserFIXTask.class.getName() + "] " + 
		            "<=ee-debug=>" + this.params + "request fail:" + resp.getMessage() + "\n");
		        } catch (Exception e1) {
		          e1.printStackTrace();
		        }
			}
		}
		reqer.close();
		latch.countDown();
	}

	private String parseDomain(String domain) {
		return domain.replaceAll("\\|", "(");
	}
}
